<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>What to buy</h1>
<p title="a gentle reminder">Don't forget to buy this stuff.</p>
<p>This is just a test</p>
<ul id="purchases">
    <li>A tin of beans</li>
    <li class="sale">Cheese</li>
    <li class="sale important">Milk</li>
</ul>
<script>
    var shopping=document.getElementById("purchases");
    var sales=getElementsByClassName(shopping,"li","sale");
    console.log(sales);
//    设计document.getElementsByClassName("classname")原生方法（此方法不适用多个类名的情况）
//    function getElementsByClassName(node,classname){
//        if(node.getElementsByClassName){
//            //使用现有方法
//            return node.getElementsByClassName(classname);
//        }else{
//            //封装一个新方法
//            var results=[];
//            var elems=node.getElementsByTagName("*");
//            for(var i=0;i<elems.length;i++){
//                if(elems[i].className.indexOf(classname)!==-1){
//                    results[results.length]=elems[i];
//                }
//            }
//            return results;
//        }
//    }


    //完善版
    //设计原生document.getElementsByClassName(classname)
    function getElementsByClassName(parent,targetName,classname){
        var classString=parent.getElementsByTagName(targetName);
        var arr=[];
        for(var i=0;i<classString.length;i++){
            var classArr=classString[i].className.split(" ");
            for(var j=0;j<classArr.length;j++){
                if(classArr[j]===classname){
                    arr.push(classString[i]);
                    break;
                }
            }

        }
        return arr;
    }
</script>
</body>
</html>